<template>
  <view class="container">
    <!-- 成功弹窗 -->
    <view v-if="showSuccessPopup" class="success-popup">
      <view class="popup-mask" @tap="showSuccessPopup = false"></view>
      <view class="popup-content">
        <image class="popup-image" :src="currentItem.image" mode="aspectFit"></image>
        <text class="popup-title">恭喜获得 {{currentItem.name}}！</text>
        <text class="popup-confirm" @tap="showSuccessPopup = false">确认</text>
      </view>
    </view>

    <!-- 积分展示 -->
    <view class="points-header">
      <text class="points-text">当前积分：{{ userPoints }}</text>
    </view>

    <!-- 导航切换 -->
    <view class="nav-tabs">
      <text 
        :class="['tab-item', activeTab === 0 ? 'active' : '']"
        @click="activeTab = 0"
      >
        可领取
      </text>
      <text 
        :class="['tab-item', activeTab === 1 ? 'active' : '']"
        @click="activeTab = 1"
      >
        已领取
      </text>
    </view>

    <!-- 商品列表 -->
    <scroll-view class="goods-list" scroll-y>
      <view 
        v-for="(item, index) in activeList"
        :key="item.id"
        class="goods-card"
      >
        <image class="goods-image" :src="item.image" mode="aspectFill"></image>
        <view class="goods-info">
          <text class="goods-title">{{ item.name }}</text>
          <text class="goods-points">需 {{ item.requiredPoints }} 积分</text>
          <text 
            v-if="activeTab === 0"
            :class="['get-btn', item.canGet ? '' : 'disabled']"
            @click="handleGet(item)"
          >
            {{ item.canGet ? '立即领取' : '积分不足' }}
          </text>
          <text v-else class="got-label">已领取</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      activeTab: 0,
      userPoints: 0,
      showSuccessPopup: false,
      currentItem: null,
      allGoods: [
        {
          id: 1,
          name: '竞技斗牛纪念卡',
          image: 'https://mp-1de2ab47-60cc-4717-bb0c-985e43d6d68e.cdn.bspapp.com/img/mine/souvenirCard/1.png',
          requiredPoints: 500,
          canGet: false,
          isReceived: false
        },
        {
          id: 2,
          name: '草原驯牛纪念卡',
          image: 'https://mp-1de2ab47-60cc-4717-bb0c-985e43d6d68e.cdn.bspapp.com/img/mine/souvenirCard/2.png',
          requiredPoints: 1000,
          canGet: false,
          isReceived: false
        }
      ],
      receivedGoods: []
    }
  },
  computed: {
    activeList() {
      return this.activeTab === 0 ? 
        this.allGoods.filter(item => !item.isReceived) : 
        this.receivedGoods
    }
  },
  methods: {
    async loadData() {
      try {
        const { result } = await uniCloud.callFunction({
          name: 'getCommemorativeCards',
          data: { action: 'list' }
        })
    
        if (result?.code === 200) {
          this.allGoods = result.data.list.map((item,index) => ({
            _id: item._id,
            id:index+1,
            name: item.name,
            image: item.image,
            requiredPoints: item.requiredPoints,
            createTime: item.createTime || Date.now(),
            desc: item.desc || '暂无描述'
          }))
        }
      } catch (error) {
        uni.showToast({ title: '数据加载失败', icon: 'none' })
      }
    },
    loadReceivedGoods() {
      const receivedIds = uni.getStorageSync('receivedGoodsIds') || []
      this.receivedGoods = this.allGoods.filter(item => 
        receivedIds.includes(item.id)
      )
      this.allGoods = this.allGoods.map(item => ({
        ...item,
        isReceived: receivedIds.includes(item.id)
      }))
    },
    saveReceivedGoods(item) {
      const receivedIds = uni.getStorageSync('receivedGoodsIds') || []
      if (!receivedIds.includes(item.id)) {
        receivedIds.push(item.id)
        uni.setStorageSync('receivedGoodsIds', receivedIds)
      }
    },
    updateGoodsAvailability() {
      this.allGoods = this.allGoods.map(item => ({
        ...item,
        canGet: this.userPoints >= item.requiredPoints
      }))
    },
    handleGet(item) {
      if (!item.canGet) {
        uni.showToast({ title: '积分不足', icon: 'none' })
        return
      }

      uni.showModal({
        title: '领取确认',
        content: `确定要领取「${item.name}」吗？`,
        success: res => {
          if (res.confirm) {
            this.saveReceivedGoods(item)
            
            this.receivedGoods.push(item)
            this.allGoods = this.allGoods.map(g => 
              g.id === item.id ? {...g, isReceived: true} : g
            )
            
            // 如果需要扣除积分，取消下面注释
            // this.userPoints -= item.requiredPoints
            
            this.currentItem = item
            this.showSuccessPopup = true
            this.updateGoodsAvailability()
          }
        }
      })
    }
  },
  async onLoad(options) {
  await this.loadData()
    this.loadReceivedGoods()
    
    if (options.userInfo) {
      try {
        const userInfo = JSON.parse(decodeURIComponent(options.userInfo))
        this.userPoints = userInfo.score || 0
        this.updateGoodsAvailability()
      } catch (e) {
        console.error('参数解析失败', e)
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  min-height: 100vh;
  position: relative;
  background-image: url('https://mp-1de2ab47-60cc-4717-bb0c-985e43d6d68e.cdn.bspapp.com/img/mine_bg.png');
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
}

.success-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

.popup-mask {
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
}

.popup-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 560rpx;
  background: #fff;
  border-radius: 24rpx;
  padding: 40rpx;
  text-align: center;
}

.popup-image {
  width: 300rpx;
  height: 300rpx;
  margin-bottom: 30rpx;
  border-radius: 16rpx;
}

.popup-title {
  display: block;
  font-size: 36rpx;
  color: #9A4E26;
  font-weight: bold;
  margin-bottom: 40rpx;
}

.popup-confirm {
  display: block;
  width: 200rpx;
  margin: 0 auto;
  padding: 20rpx 0;
  background: #9A4E26;
  color: #fff;
  border-radius: 48rpx;
  font-size: 32rpx;
  transition: opacity 0.2s;
}

.popup-confirm:active {
  opacity: 0.8;
}

.points-header {
  background-color: #FEF6EF;
  padding: 30rpx;
  border-radius: 16rpx;
  margin: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}

.points-text {
  font-size: 36rpx;
  color: #6b4200;
  font-weight: bold;
}

.nav-tabs {
  display: flex;
  margin: 30rpx 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
  background-color: rgba(255, 255, 255, 0.9);
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 24rpx;
  font-size: 32rpx;
  color: #666;
  transition: all 0.3s;
}

.active {
  color: #9A4E26;
  font-weight: bold;
  background-color: #FEF6EF;
}

.goods-list {
  height: calc(100vh - 300rpx);
}

.goods-card {
  background-color: #FEF6EF;
  border-radius: 16rpx;
  margin: 20rpx;
  display: flex;
  padding: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.goods-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.goods-points {
  font-size: 28rpx;
  color: #9A4E26;
}

.get-btn {
  align-self: flex-start;
  background-color: #9A4E26;
  color: #fff;
  padding: 12rpx 36rpx;
  border-radius: 24rpx;
  font-size: 28rpx;
  transition: opacity 0.2s;
}

.get-btn:active {
  opacity: 0.8;
}

.disabled {
  background: #ccc;
  color: #666;
}

.got-label {
  color: #666;
  font-size: 28rpx;
}
</style>